package mianshi;

/**
 * 二分查找
 */
public class TwoSelect {
    public static void main(String[] args) {
        int[] arr = {5, 7, 7, 8, 10};
        int target = 8;
        System.out.println(getIndex(arr, target));
    }

    public static int getIndex(int[] arr, int target) {
        int index = 0;
        // 左右起始节点
        int left = 0;
        int right = arr.length - 1;
        while (left <= right) {
            // 找中间点
            int mid = left + (right - left) / 2;
            if (arr[mid] > target) {
                right = mid - 1;
            } else if (arr[mid] < target) {
                left = mid + 1;
            } else if (arr[mid] == target) {
                index = mid;
                return index;
            }
        }
        return index;
    }
}
